#include "camera.h"
#include "ui_camera.h"

camera::camera(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::camera)
{
    ui->setupUi(this);
    mycamera=new v4l2camera();
    connect(mycamera,&v4l2camera::sendimage,this,&camera::showimage);
    connect(this,SIGNAL(stop_camera()),mycamera,SLOT(stop_signal()));
    connect(mycamera,SIGNAL(thread_complete()),this,SLOT(clearlabel()));
    ui->pushButton->setEnabled(true);
    ui->pushButton_2->setEnabled(false);
    ui->pushButton_3->setEnabled(false);
}

camera::~camera()
{
    mycamera->wait();
    delete ui;
}

void camera::showimage(QImage image)
{

    myimage = image.mirrored(true, true);
    QPixmap pixmap=QPixmap::fromImage(myimage).scaled(ui->label->size());
    ui->label->setPixmap(pixmap);
}

void camera::on_pushButton_clicked()
{
    // if(!mycamera->isRunning())
    // {
    //     qDebug()<<"thread start";
    //
    // }
    // else
    //     qDebug()<<"thread exist";
     mycamera->start();
    ui->pushButton->setEnabled(false);
    ui->pushButton_2->setEnabled(true);
    ui->pushButton_3->setEnabled(true);
}


void camera::on_pushButton_2_clicked()
{

    QDateTime mycurrentTime = QDateTime::currentDateTime();
    QString fileName = mycurrentTime.toString("yyyyMMdd_hhmmss") + ".jpg";
    QString filePath = saveDir + "/" + fileName;

    if (!myimage.save(filePath)) {
        qDebug() << "Failed to save image to" << filePath;
    }
    emit photoupdate();
}


void camera::on_pushButton_3_clicked()
{
    mycamera->requestInterruption();
    while(mycamera->isRunning())
    {

    }
    ui->pushButton->setEnabled(true);
    ui->pushButton_2->setEnabled(false);
    ui->pushButton_3->setEnabled(false);
}

void camera::clearlabel()
{
    ui->label->clear();
}



